package com.xc.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.xc.common.Const;
import com.xc.common.ServerResponse;
import com.xc.dao.SiteSmsLogMapper;
import com.xc.pojo.SiteSmsLog;
import com.xc.service.ISmsService;
import com.xc.utils.DateTimeUtil;
import com.xc.utils.redis.RedisConst;
import com.xc.utils.redis.RedisShardedPoolUtils;
import com.xc.utils.sms.ali.AliyunSms;
import com.xc.utils.sms.ali.AliyunSmsConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/17 12:00 PM
 */
@Service("iSmsService")
@Slf4j
public class SmsServiceImpl implements ISmsService {

    @Autowired
    SiteSmsLogMapper siteSmsLogMapper;

    @Override
    public ServerResponse sendAliyunSMS(String phoneNum, String ali_template) {
        // TODO: 2018/3/20 控制短信发送频率
        if(StringUtils.isBlank(phoneNum)) return ServerResponse.createByErrorMsg("发送失败，手机号不能为空");

        String yzmCode = RandomStringUtils.randomNumeric(4);
//        System.out.println("验证码："+yzmCode);

        SendSmsResponse response = null;
        try {
            response = AliyunSms.sendSms(phoneNum, AliyunSmsConst.SIGN_NAME
                    ,ali_template , yzmCode);
        }catch (Exception e){
            log.error("发送短信异常：{}",e);
        }
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        if(response.getCode() != null && response.getCode().equals("OK")) {
            String keys = Const.SmsKeyPrefix.ALIYUN_PREFIX + phoneNum;
            RedisShardedPoolUtils.setEx(keys, yzmCode,
                    RedisConst.RedisCacheExTime.REDIS_SESSION_EXTIME);
            // 保存发送日志
            SiteSmsLog siteSmsLog = new SiteSmsLog();
            siteSmsLog.setSmsPhone(phoneNum);
            siteSmsLog.setSmsTitle("注册验证码");
            siteSmsLog.setSmsCnt(yzmCode);
            siteSmsLog.setSmsTemplate(ali_template);
            siteSmsLog.setSmsStatus(0);
            siteSmsLog.setAddTime(DateTimeUtil.getCurrentDate());
            siteSmsLogMapper.insert(siteSmsLog);

            return ServerResponse.createBySuccessMsg("发送成功");
        }else{
            return ServerResponse.createByErrorMsg("短信发送失败，请重试");
        }
    }



}


